package san.java.day13;

import jdk.nashorn.internal.ir.CallNode;

import java.io.*;

/**
 * 转换流: 提供了在字节流和字符流之间的转换
 *  InputStreamReader 和 OutputStreamWriter
 *  2. 字节流中的数据都是字符时,转换为字符流操作更高效
 *
 *  InputStreamReader:
 *      用于将字节流中读取到的字节按照指定字符集解码成字符. 需要和InputStream"套接"
 *
 *      构造方法:
 *          InputStreamReader(InputStream in)
 *          public InputStreamReader(InputStream in, String charsetName)
 *
 * 注意:
 *  1. 在转换字符流的时候,设置的字符集编码要与读取的文件的数据的编码一致,不然会出现乱码
 *
 */

public class TransportStream_03 {

    /**
     * 转换字节输入流
     * @throws Exception
     */
    public static void testInputStreamReader() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("data/a1.txt");

        // 把字节流转换为字符流
        InputStreamReader in = new InputStreamReader(fileInputStream, "UTF-8");

        char[] c = new char[100];
        int len = 0;

        while ((len = in.read(c)) != -1) {
            System.out.println(new String(c, 0, len));
        }

        in.close();
        fileInputStream.close();
    }

    /**
     * 转换字节输出流为字符输出流
     */
    public static void testOutputStreamWriter() throws IOException {

        FileOutputStream out = new FileOutputStream("data/a6.txt");

        OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8");

        os.write("你好, 你好");
        os.flush();
        os.close();
        out.close();

    }

    public static void main(String[] args) {
        try {
            testInputStreamReader();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            testOutputStreamWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
